/**
 *
 * 数据统计相关接口
 */

import request from "@/router/axios";
import { Message } from "element-ui";
import ActionTypes from "@/const/action";
function noThousand(number) {
  if (typeof number !== "number") {
    return number;
  }
  return ~~(number / 1000) * 1000;
}

function postDataFormat(data, action) {
  let postData = {};
  let { startTime, endTime } = data;
  if (startTime && endTime) {
    if (new Date(endTime).getTime() < new Date(startTime).getTime()) {
      Message({
        type: "warning",
        message: "开始时间不能大于结束时间",
      });
      return false;
    }
  }
  if (startTime) {
    postData.startTime = new Date(noThousand(new Date(startTime).getTime()));
  }
  if (endTime) {
    postData.endTime = new Date(
      noThousand(new Date(endTime).getTime()) + (24 * 60 * 60 - 1) * 1000
    );
  }

  if (startTime && !endTime) {
    postData.endTime = new Date(noThousand(new Date().getTime()));
  }

  if (!startTime && endTime) {
    postData.startTime = new Date(
      noThousand(new Date("1970-01-01 00:00:00").getTime())
    );
  }
  if (
    action === ActionTypes.STATISTICS_MERCHANT ||
    action === ActionTypes.STATISTICS_USER
  ) {
    if (!startTime && !endTime) {
      postData.endTime = new Date(noThousand(new Date().getTime()));
      postData.startTime = new Date(
        postData.endTime.getTime() - 24 * 60 * 60 * 1000
      );
    }
  }
  return postData;
}

const GETTER_URL_MAP = {
  /**@desc 用户数据统计 */
  [ActionTypes.STATISTICS_USER]: "/admin/userStatistics/query",
  /**@desc 获取商家数据统计 */
  [ActionTypes.STATISTICS_MERCHANT]: "/admin/merchant/statistics",
  /**@desc 获取维修统计*/
  [ActionTypes.STATISTICS_SERVICE]: "/admin/maintainOrder/exhibitionStatistics",
  /**@desc 获取维修类型统计 */
  [ActionTypes.STATISTICS_TYPE]: "/admin/maintainOrder/typeStatistics",
  /**@desc 地域统计统计 */
  [ActionTypes.STATISTICS_RANGE]: "/admin/order/rangeStatistics",
  /**@desc 商品统计 */
  [ActionTypes.STATISTICS_GOODS]: "/admin/order/productStatistics",
  /**@desc 展会统计 */
  [ActionTypes.STATISTICS_EXHIBITION]: "/admin/order/exhibitionStatistics",
  /**@desc 数据统计 */
  [ActionTypes.STATISTICS_DATE]: "/admin/order/statistics",
};

// 获取用户数据统计
export const SyncGetStatisticsData = (action, data) => {
  data = postDataFormat(data, action);
  if (data === false) {
    return;
  }

  return request({
    url: GETTER_URL_MAP[action] || "",
    data: data,
    method: "POST",
    headers: {
      "Content-Type": "application/json;",
    },
  })
    .then((res) => ({
      data: res.data.data,
    }))
    .catch((error) => ({
      error,
    }));
};
